package cn.cutie.clotconfig.client.config;

import cn.cutie.clotconfig.client.value.SpringValue;
import cn.cutie.clotconfig.client.value.SpringValueProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Arrays;
import java.util.Optional;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/5/10 20:42
 * @Version: 0.0.1
 */
public class ClotConfigRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        System.out.println("[CLOTCONFIG] register PropertySourcesProcessor");
        registerClass(registry, PropertySourcesProcessor.class);
        registerClass(registry, SpringValueProcessor.class);
    }

    private static void registerClass(BeanDefinitionRegistry registry, Class propertySourcesProcessorClass) {
        System.out.println("[CLOTCONFIG] register " + propertySourcesProcessorClass.getName());
        Optional<String> first = Arrays.stream(registry.getBeanDefinitionNames())
                .filter(x -> x.equals(propertySourcesProcessorClass.getName())).findFirst();
        if (first.isPresent()){
            System.out.println("[CLOTCONFIG] " + propertySourcesProcessorClass.getName() + "registered already");
            return;
        }
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(propertySourcesProcessorClass).getBeanDefinition();
        registry.registerBeanDefinition(propertySourcesProcessorClass.getName(), beanDefinition);
    }
}
